package com.gr.staffpm.projects.model;

import org.apache.shiro.SecurityUtils;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.gr.staffpm.datatypes.Project;
import com.gr.staffpm.pages.projects.ViewProject;
import com.gr.staffpm.security.constants.StaffPMRoles;
import com.gr.staffpm.security.service.UserService;


public class ProjectLink extends Link<Project> {

    private final UserService userService;

    /**
     * @param id
     * @param model
     * @see org.apache.wicket.Component#Component(String, IModel)
     */
    public ProjectLink(final String id, IModel<Project> model, UserService userService) {
        super(id, model);
        this.userService = userService;
    }

    /**
     * @param id
     * @param project
     */
    public ProjectLink(String id, Project project, UserService userService) {
        this(id, new Model<Project>(project), userService);
    }

    private static final long serialVersionUID = 1L;

    @Override
    public void onClick() {
        Project p = getModelObject();
        boolean owner = userService.getCurrentUser().equals(p.getOwner());
        boolean admin = SecurityUtils.getSubject().hasRole(StaffPMRoles.ADMIN);

        if (SecurityUtils.getSubject().isPermitted("project:read:" + p.getProjectId()) || admin || owner) {
            setResponsePage(new ViewProject(new PageParameters("id=" + String.valueOf(p.getProjectId()))));
        } else
            error("You do not have permission to read project: " + p.getProjectName());
    }

}
